package org.nutz.quickstart.auth;

import javax.servlet.http.HttpSession;

import org.nutz.dao.Cnd;
import org.nutz.dao.tools.Tables;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Param;
import org.nutz.quickstart.auth.bean.User;
import org.nutz.service.IdNameEntityService;

@InjectName
@IocBean(field="dao",create="init")
@At("/auth")
public class AuthModule extends IdNameEntityService<User>{
	
	private static final Log log = Logs.getLog(AuthModule.class);
	
	@At
	public boolean login(@Param("username") String userName, 
						   @Param("password") String password,
						   HttpSession session){
		User user = dao().fetch(User.class, Cnd.where("username", "like", userName).and("password","like",password));
		if (user != null) {
			session.setAttribute(User.class.getName(), user);
			if (log.isDebugEnabled())
				log.debugf("%s login success!",userName);
			return true;
		}
		return false;
	}
	
	@At
	public void logout(HttpSession session){
		session.invalidate();
	}
	
	public void init(){
		if(!dao().exists(User.class)){
			//POJO-->DB
			Tables.define(dao(), Tables.parse(User.class));
			//Create Default admin user
			User user = new User();
			user.setUsername("admin");
			user.setPassword("admin");
			user.setNote("Default admin user");
			dao().insert(user);
		}
	}
}
